import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Button,
  Space,
  Typography,
  Select,
  Avatar,
  Spin,
  Empty,
} from 'antd';
import { Link } from 'react-router-dom';
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  BarChartOutlined,
  TeamOutlined,
  UserOutlined,
  PlayCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { analysisApi, teamApi } from '../services/api';

const { Text } = Typography;

interface DashboardStats {
  overview: {
    totalPoints: number;
    analyzedPoints: number;
    notAnalyzedPoints: number;
    needsCollectionPoints: number;
    notNeededPoints: number;
    analysisProgress: number;
  };
  byType: {
    UMA: number;
    UKM: number;
  };
  byTeam: Array<{
    teamId: string;
    teamName: string;
    totalPoints: number;
    analyzedPoints: number;
    analysisProgress: number;
    seMembers?: string;
  }>;
  recentActivity: Array<{
    id: string;
    type: 'point_analyzed' | 'extraction_completed' | 'team_member_added';
    title: string;
    description: string;
    timestamp: string;
    metadata?: Record<string, any>;
  }>;
  trends: Array<{
    date: string;
    analyzed: number;
    extracted: number;
  }>;
}

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [selectedTeam, setSelectedTeam] = useState<string>('all');
  const [dateRange, setDateRange] = useState<string>('all'); // 改为字符串类型，避免对象引用问题
  const [userTeams, setUserTeams] = useState<any[]>([]);
  const isLoadingRef = useRef(false); // 防止重复请求的ref

  // 加载仪表板数据
  const loadDashboardData = useCallback(async () => {
    // 防止重复请求
    if (isLoadingRef.current) {
      console.log('📊 [Dashboard] Skipping request - already loading');
      return;
    }

    try {
      isLoadingRef.current = true;
      setLoading(true);
      console.log('📊 [Dashboard] Starting data load...');

      const [statsResponse, teamsResponse, teamStatsResponse] = await Promise.all([
        analysisApi.getAnalysisStats(),
        teamApi.getTeams(),
        analysisApi.getTeamAnalysisStats()
      ]);

      console.log('📊 [Dashboard] API Responses:', { statsResponse, teamsResponse, teamStatsResponse });

      if (statsResponse && (statsResponse.data || statsResponse.success)) {
        // API response structure: {success: true, data: {total_metrics: 23455, by_type: {...}, by_analysis_status: {...}}}
        const apiData: any = statsResponse.data || statsResponse;
        console.log('📊 [Dashboard] Processing API data:', apiData);

        // 计算各项统计，避免重复计数
        const notAnalyzedStatus = apiData.by_analysis_status?.not_analyzed || 0;
        const needsCollectionStatus = apiData.by_analysis_status?.needs_collection || 0;
        const notNeededStatus = apiData.by_analysis_status?.not_needed || 0;

        // analyzed状态就是not_needed，不需要重复计算
        const analyzedStatus = notNeededStatus;

        // 已完成分析的数量 = not_needed (实际的analyzed状态)
        const completedAnalysis = analyzedStatus;

        
        const transformedStats: DashboardStats = {
          overview: {
            totalPoints: apiData.total_metrics || 0,
            analyzedPoints: completedAnalysis, // 只计算not_needed作为已分析
            notAnalyzedPoints: notAnalyzedStatus,
            needsCollectionPoints: needsCollectionStatus,
            notNeededPoints: notNeededStatus,
            analysisProgress: apiData.total_metrics > 0
              ? Math.round(completedAnalysis / apiData.total_metrics * 100)
              : 0,
          },
          byType: {
            UMA: apiData.by_type?.histogram || 0,  // 只包含直方图，不包含枚举
            UKM: apiData.by_type?.ukm_event || 0,  // UKM事件
          },
          byTeam: teamStatsResponse?.data || [], // Get from new team stats API
          recentActivity: [
            {
              id: '1',
              type: 'extraction_completed',
              title: '遥测点数据提取完成',
              description: `成功提取 ${apiData.total_metrics || 0} 个遥测点，包含 ${(apiData.by_type?.histogram || 0)} 个UMA直方图，${(apiData.by_type?.ukm_event || 0)} 个UKM事件`,
              timestamp: new Date().toISOString(),
            },
            {
              id: '2',
              type: 'point_analyzed',
              title: '系统分析状态初始化',
              description: `为所有遥测点初始化分析状态，${apiData.by_analysis_status?.not_analyzed || 0} 个遥测点等待分析`,
              timestamp: new Date(Date.now() - 3600000).toISOString(),
            }
          ], // Realistic mock activity
          trends: [], // TODO: Get from API
        };
        console.log('📊 [Dashboard] Transformed stats:', transformedStats);
        setStats(transformedStats);
      }
      if (teamsResponse && Array.isArray(teamsResponse)) {
        setUserTeams(teamsResponse);
      }
    } catch (error: any) {
      console.error('❌ [Dashboard] Failed to load dashboard data:', error);
      // 静默处理错误，避免影响用户体验
    } finally {
      setLoading(false);
      isLoadingRef.current = false;
    }
  }, []); // 空依赖数组，因为函数内部不依赖任何外部变量

  useEffect(() => {
    // 只在组件挂载时或筛选条件真正改变时才执行
    loadDashboardData();
  }, [selectedTeam, dateRange, loadDashboardData]);

  
  // 处理开始分析操作
  const handleStartAnalysis = (teamId: string, teamName: string) => {
    // 导航到遥测点列表页面，并设置团队过滤条件
    navigate('/analysis/points', {
      state: {
        teamFilter: teamId,
        teamName: teamName
      }
    });
  };

  // 团队表格列
  const teamColumns: ColumnsType<any> = [
    {
      title: '团队名称',
      dataIndex: 'teamName',
      key: 'teamName',
      render: (text) => (
        <Space>
          <Avatar icon={<TeamOutlined />} size="small" />
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: '团队SE',
      dataIndex: 'seMembers',
      key: 'seMembers',
      render: (seMembers) => (
        <Space>
          <Avatar icon={<UserOutlined />} size="small" />
          <Text>{seMembers || '-'}</Text>
        </Space>
      ),
    },
    {
      title: '总遥测点',
      dataIndex: 'totalPoints',
      key: 'totalPoints',
      render: (value) => <Text>{value}</Text>,
    },
    {
      title: '已分析',
      dataIndex: 'analyzedPoints',
      key: 'analyzedPoints',
      render: (value) => <Text style={{ color: '#52c41a' }}>{value}</Text>,
    },
    {
      title: '分析进度',
      dataIndex: 'analysisProgress',
      key: 'analysisProgress',
      render: (value, record) => (
        <Progress
          percent={value}
          size="small"
          status={record.totalPoints === 0 ? 'normal' : value >= 80 ? 'success' : value >= 50 ? 'active' : 'exception'}
          format={(percent) => record.totalPoints === 0 ? '-' : `${percent}%`}
        />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Link to={`/analysis/points?teamId=${record.teamId}`}>
          <Button
            type="primary"
            size="small"
            icon={<PlayCircleOutlined />}
          >
            开始分析
          </Button>
        </Link>
      ),
    },
  ];

  if (loading && !stats) {
    return (
      <div style={{ textAlign: 'center', padding: '100px' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>
          <Text>加载仪表板数据...</Text>
        </div>
      </div>
    );
  }

  const overview = stats?.overview || {
    totalPoints: 0,
    analyzedPoints: 0,
    notAnalyzedPoints: 0,
    needsCollectionPoints: 0,
    notNeededPoints: 0,
    analysisProgress: 0,
  };

  return (
    <div style={{ maxWidth: 1400, margin: '0 auto' }}>

      {/* 概览统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总遥测点"
              value={overview.totalPoints}
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
            <div style={{ marginTop: '12px', fontSize: '12px', color: '#666' }}>
              <Row gutter={8}>
                <Col span={12}>
                  <div style={{ textAlign: 'center' }}>
                    <Avatar size="small" style={{ backgroundColor: '#1890ff', marginBottom: '4px' }}>U</Avatar>
                    <div>UMA: <span style={{ fontWeight: 'bold', color: '#1890ff' }}>{stats?.byType.UMA || 0}</span></div>
                  </div>
                </Col>
                <Col span={12}>
                  <div style={{ textAlign: 'center' }}>
                    <Avatar size="small" style={{ backgroundColor: '#52c41a', marginBottom: '4px' }}>K</Avatar>
                    <div>UKM: <span style={{ fontWeight: 'bold', color: '#52c41a' }}>{stats?.byType.UKM || 0}</span></div>
                  </div>
                </Col>
              </Row>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成分析"
              value={overview.analyzedPoints}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
            <div style={{ marginTop: '12px', fontSize: '12px', color: '#666' }}>
              <Row gutter={8}>
                <Col span={12}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ color: '#722ed1', fontWeight: 'bold' }}>{overview.notNeededPoints}</div>
                    <div>无需收集</div>
                  </div>
                </Col>
                <Col span={12}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ color: '#ff7a45', fontWeight: 'bold' }}>{overview.needsCollectionPoints}</div>
                    <div>需要收集</div>
                  </div>
                </Col>
              </Row>
            </div>
            <div style={{ marginTop: '8px' }}>
              <Progress
                percent={overview.analysisProgress}
                size="small"
                showInfo={false}
              />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待分析"
              value={overview.notAnalyzedPoints}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 团队分析状态 */}
      <Row gutter={16}>
        <Col span={24}>
          <Card
            title="团队分析状态"
            extra={
              <Space>
                <Button type="primary" onClick={() => navigate('/analysis/points')}>
                  开始分析
                </Button>
                <Button
                  type="link"
                  onClick={() => navigate('/teams')}
                  icon={<EyeOutlined />}
                >
                  查看所有团队
                </Button>
              </Space>
            }
          >
            {stats?.byTeam && stats.byTeam.length > 0 ? (
              <Table
                columns={teamColumns}
                dataSource={stats.byTeam}
                rowKey="teamId"
                pagination={false}
                size="small"
                locale={{
                  emptyText: '暂无团队数据'
                }}
              />
            ) : (
              <Empty
                description="暂无团队数据"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;